package cContext

import (
	"fmt"
	"net/http"
	"time"

	"github.com/gin-gonic/gin"
	"github.com/google/uuid"

	"gitee.com/csingo/cCommon"
	"gitee.com/csingo/cHelper"
)

func New() *gin.Context {
	ctx := &gin.Context{}
	ctx.Request = &http.Request{
		Method: http.MethodPost,
		Header: http.Header{},
	}

	traceid := CreateTraceId()
	ctx.Set(cCommon.XIndex_TraceId, traceid)

	return ctx
}

func CreateTraceId() string {
	var traceid string

	random := cHelper.RandomInt(0, 999999)
	id, err := uuid.NewUUID()
	if err != nil {
		now := time.Now().UnixNano()
		traceid = fmt.Sprintf("%d%06d", now, random)
	} else {
		traceid = fmt.Sprintf("%06d-%s", random, id.String())
	}

	return traceid
}

func GetTraceId(ctx *gin.Context) string {
	traceid := ctx.GetString(cCommon.XIndex_TraceId)

	if traceid == "" {
		traceid = ctx.Request.Header.Get(cCommon.XIndex_TraceId)
	}

	if traceid == "" {
		traceid = CreateTraceId()
	}
	ctx.Set(cCommon.XIndex_TraceId, traceid)

	return traceid
}
